package com.easyui.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import com.easyui.common.UserLogin;

public class LoginServlet extends HttpServlet {

	public LoginServlet() {}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/json;charset=utf-8");
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		
		String action = request.getParameter("action");
		
		JSONObject jsonAll = null;
		boolean success = false;
		String msg = "";
		
		if (action != null && action.equals("login")) {
			String userID = request.getParameter("username");
			String password = request.getParameter("password");
			String role = request.getParameter("role");
			
			int result = new UserLogin().check(role, userID, password);
			if (result == 1) {
				//查询用户名
				HttpSession session = request.getSession(); //获的session
				session.setAttribute("role", role);
				session.setAttribute("userID", userID);
				success = true;
				msg = "登录成功";
			} else {
				success = false;
				if(result == 2) {
					msg = "密码错误,请重新输入.";
				} else if(result == 3) {
					msg = "没有该用户,请检查角色是否选择正确.";
				}
			}
		} else {
			success = false;
			msg = "登录失败";
		}
		
		//msg = new String(msg.getBytes("ISO-8859-1"), "utf-8");
		
		jsonAll = new JSONObject();
		jsonAll.put("success", success);
		jsonAll.put("msg", msg);
		
		out.print(jsonAll);
		out.flush();
		out.close();
	}

	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {
		doPost(request, response);
	}
}
